package com.dhruvtaara.beta.toolset;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class DefaultEncryption {

	/**
	 * 
	 */
	private static final AppLog logger = new AppLog(
			DefaultEncryption.class.getName());

	/***
	 * 
	 * @param data
	 * @return
	 */
	public static String encrypt(String data) {
		String result = null;
		try {
			MessageDigest md5 = MessageDigest.getInstance("md5");
			try {
				md5.reset();
				byte[] dataBytes = md5.digest(data.getBytes("utf-8"));
				StringBuffer buffer = new StringBuffer();
				for (int i = 0; i < dataBytes.length; ++i) {
					buffer.append(Integer.toHexString(
							(dataBytes[i] & 0xFF) | 0x100).substring(1, 3));
				}
				result = buffer.toString();
			} catch (UnsupportedEncodingException e) {
				logger.Error(String.format("Could not create MD5 digest [{0}]",
						e.getMessage()));
			}
		} catch (NoSuchAlgorithmException e) {
			logger.Error(String.format("MD5 encryption is not available [{0}]",
					e.getMessage()));
		}
		return result;
	}

	/**
	 * 
	 * @param rawData
	 * @param encryptedData
	 * @return
	 */
	public static boolean areSame(String rawData, String encryptedData) {
		rawData = DefaultEncryption.encrypt(rawData);
		return rawData.compareTo(encryptedData) == 0;
	}
}
